#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: zhangZW
@file: check.py
@time: 2023/01/20
@des: 检测 本地客户端 selenium-server 情况，用于通信远程客户端
"""
import subprocess
import time

import redis

from scripts import tools
from scripts.tools import get_system, readini


def check():
    if get_system() == 'Linux':
        command = f'netstat -anp | grep {readini().getint("client", "port")}'
    elif get_system() == "Windows":
        command = f'netstat -aon|findstr {readini().getint("client", "port")}'
    else:
        print('目前不支持此非Windows/Linux系统!')
        return None
    secret = tools.readini().get('client', 'secret')
    server_ip = tools.analyse_b64(secret).split(',')[1]
    # 初始化redis，保存设备链接信息
    redis_client = redis.Redis(
        # host=server_ip,
        host='127.0.0.1',
        port=tools.readini().getint('redis', 'port'),
        db=0,
        # password=tools.readini().get('redis', 'password'),
    )
    while True:
        output = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        command_str = output.stdout.readlines()
        if command_str:
            # 存放链接信息
            if redis_client.sismember('client_secret', secret):
                pass
            else:
                redis_client.sadd('client_secret', secret)
            time.sleep(10)
        else:
            if redis_client.sismember('client_secret', secret):
                redis_client.srem('client_secret', secret)
            else:
                pass
            break






if __name__ == '__main__':
    check()
